<template>
  <div class="area-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <h2>区域管理</h2>
          <el-button type="primary" @click="showCreateDialog" v-if="authStore.user?.role === 'admin'">
            <el-icon><Plus /></el-icon>
            新增区域
          </el-button>
        </div>
      </template>

      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-input
          v-model="searchQuery"
          placeholder="搜索区域名称"
          style="width: 300px"
          clearable
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-button @click="loadAreas" style="margin-left: 10px">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>

      <!-- 区域列表 -->
      <el-table :data="areas" v-loading="loading" style="width: 100%">
        <el-table-column prop="name" label="区域名称" width="200" />
        <el-table-column prop="leader_name" label="组长" width="150">
          <template #default="{ row }">
            <span v-if="row.leader_name">{{ row.leader_name }}</span>
            <span v-else class="text-gray">未设置</span>
          </template>
        </el-table-column>
        <el-table-column prop="member_count" label="成员数量" width="120">
          <template #default="{ row }">
            <el-tag type="info">{{ row.member_count }}人</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" min-width="200">
          <template #default="{ row }">
            <span v-if="row.description">{{ row.description }}</span>
            <span v-else class="text-gray">无描述</span>
          </template>
        </el-table-column>
        <el-table-column prop="is_active" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.is_active ? 'success' : 'danger'">
              {{ row.is_active ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" v-if="authStore.user?.role === 'admin'">
          <template #default="{ row }">
            <el-button size="small" @click="viewAreaMembers(row)">
              查看成员
            </el-button>
            <el-button size="small" type="primary" @click="editArea(row)">
              编辑
            </el-button>
            <el-button size="small" type="danger" @click="deleteArea(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" v-else>
          <template #default="{ row }">
            <el-button size="small" @click="viewAreaMembers(row)">
              查看成员
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 创建/编辑区域对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEditing ? '编辑区域' : '新增区域'"
      width="600px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="区域名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入区域名称" />
        </el-form-item>
        <el-form-item label="组长" prop="leader_id">
          <el-select
            v-model="form.leader_id"
            placeholder="请选择组长"
            clearable
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="user in userOptions"
              :key="user.id"
              :label="`${user.name} (${user.username})`"
              :value="user.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入区域描述"
          />
        </el-form-item>
        <el-form-item label="状态" prop="is_active">
          <el-switch
            v-model="form.is_active"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          {{ isEditing ? '更新' : '创建' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 区域成员对话框 -->
    <el-dialog
      v-model="membersDialogVisible"
      :title="`${selectedArea?.name} - 成员列表`"
      width="800px"
    >
      <el-table :data="areaMembers" v-loading="membersLoading">
        <el-table-column prop="name" label="姓名" width="120" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="employee_id" label="工号" width="120" />
        <el-table-column prop="position" label="职位" width="150" />
        <el-table-column prop="department" label="部门" width="120" />
        <el-table-column prop="phone" label="电话" width="150" />
      </el-table>
      <template #footer>
        <el-button @click="membersDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh } from '@element-plus/icons-vue'
import { areasApi, usersApi } from '@/api'
import { useAuthStore } from '@/stores/auth'

interface Area {
  id: number
  name: string
  leader_id?: number
  leader_name?: string
  leader_username?: string
  description?: string
  is_active: boolean
  member_count: number
  created_at: string
  updated_at: string
}

interface User {
  id: number
  name: string
  username: string
  employee_id: string
  position: string
  department: string
  phone: string
  email: string
  role: string
  is_active: boolean
}

const authStore = useAuthStore()

// 数据
const areas = ref<Area[]>([])
const userOptions = ref<User[]>([])
const areaMembers = ref<User[]>([])
const selectedArea = ref<Area | null>(null)

// 状态
const loading = ref(false)
const membersLoading = ref(false)
const submitting = ref(false)
const dialogVisible = ref(false)
const membersDialogVisible = ref(false)
const isEditing = ref(false)

// 搜索和分页
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 表单
const formRef = ref()
const form = ref({
  name: '',
  leader_id: undefined as number | undefined,
  description: '',
  is_active: true
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入区域名称', trigger: 'blur' },
    { min: 1, max: 100, message: '区域名称长度在 1 到 100 个字符', trigger: 'blur' }
  ]
}

// 加载区域列表
const loadAreas = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      per_page: pageSize.value,
      search: searchQuery.value
    }
    
    const response = await areasApi.getAreas(params)
    console.log('API Response Data:', response.data);
    areas.value = response.data.areas || response.data
    total.value = response.data.total || 0
  } catch (error: any) {
    console.error('加载区域列表失败:', error)
    ElMessage.error('加载区域列表失败')
  } finally {
    loading.value = false
  }
}

// 加载用户选项
const loadUserOptions = async () => {
  try {
    const response = await usersApi.getUsers({ per_page: -1 })
    const users = response.data.users || response.data
    userOptions.value = Array.isArray(users) ? users.filter((user: User) => user.is_active) : []
  } catch (error: any) {
    console.error('加载用户选项失败:', error)
    ElMessage.error('加载用户选项失败')
  }
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  loadAreas()
}

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
  loadAreas()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  loadAreas()
}

// 显示创建对话框
const showCreateDialog = () => {
  isEditing.value = false
  dialogVisible.value = true
  loadUserOptions()
}

// 编辑区域
const editArea = (area: Area) => {
  isEditing.value = true
  selectedArea.value = area
  form.value = {
    name: area.name,
    leader_id: area.leader_id,
    description: area.description || '',
    is_active: area.is_active
  }
  dialogVisible.value = true
  loadUserOptions()
}

// 查看区域成员
const viewAreaMembers = async (area: Area) => {
  selectedArea.value = area
  membersLoading.value = true
  membersDialogVisible.value = true
  
  try {
    const response = await areasApi.getAreaMembers(area.id)
    areaMembers.value = response.data.members || response.data
  } catch (error: any) {
    console.error('加载区域成员失败:', error)
    ElMessage.error('加载区域成员失败')
  } finally {
    membersLoading.value = false
  }
}

// 删除区域
const deleteArea = async (area: Area) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除区域 "${area.name}" 吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await areasApi.deleteArea(area.id)
    ElMessage.success('删除成功')
    loadAreas()
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除区域失败:', error)
      ElMessage.error(error.response?.data?.error || '删除失败')
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    if (isEditing.value && selectedArea.value) {
      await areasApi.updateArea(selectedArea.value.id, form.value)
      ElMessage.success('更新成功')
    } else {
      await areasApi.createArea(form.value)
      ElMessage.success('创建成功')
    }
    
    dialogVisible.value = false
    loadAreas()
  } catch (error: any) {
    console.error('提交失败:', error)
    ElMessage.error(error.response?.data?.error || '操作失败')
  } finally {
    submitting.value = false
  }
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  form.value = {
    name: '',
    leader_id: undefined,
    description: '',
    is_active: true
  }
  selectedArea.value = null
}

// 初始化
onMounted(() => {
  loadAreas()
})
</script>

<style scoped>
.area-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.text-gray {
  color: #909399;
}
</style>